//
//  JJWebViewController.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/19.
//

import UIKit
@preconcurrency import WebKit

open class JJWebViewController: JJBaseViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate {
    private var url: String?
    private var titleStr: String?
    
    lazy var webView: WKWebView = {
        // 创建WKPreferences
        let preferences = WKPreferences()
        // 开启js
        preferences.javaScriptEnabled = true
        // 创建WKWebViewConfiguration
        let configuration = WKWebViewConfiguration()
        // 设置WKWebViewConfiguration的WKPreferences
        configuration.preferences = preferences
        // 创建WKUserContentController
        let userContentController = WKUserContentController()
        // 配置WKWebViewConfiguration的WKUserContentController
        configuration.userContentController = userContentController
        // 给WKWebView与Swift交互起一个名字：callbackHandler，WKWebView给Swift发消息的时候会用到
        
        // 此句要求实现WKScriptMessageHandler协议
        configuration.userContentController.add(self, name: "callbackHandler")
        // 创建WKWebView
        var webView = WKWebView(frame:CGRect.zero, configuration: configuration)
        // 让webview翻动有回弹效果
        webView.scrollView.bounces = true
        // 只允许webview上下滚动
        webView.scrollView.alwaysBounceVertical = true
        // 允许右滑返回上个页面
        webView.allowsBackForwardNavigationGestures = true
        // 此句要求实现WKNavigationDelegate协议
        webView.navigationDelegate = self
        webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)
        return webView
    }()
    
    // 进度条
    lazy var progressView: UIProgressView = {
        var progressView = UIProgressView()
        progressView.progressTintColor = UIColor.red
        progressView.trackTintColor = UIColor.clear
        return progressView
    }()
    
    public init(title: String?, url: String) {
        super.init(nibName: nil, bundle: nil)
        self.titleStr = title
        if let string = titleStr, !string.isEmpty {
            self.title = string
        }
        self.url = url
    }
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        initInterface()
        fd_interactivePopDisabled = true
    }
    
    public override func goBack() {
        if self.webView.canGoBack {
            self.webView.goBack()
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func initInterface() -> () {
        self.view.addSubview(self.webView);
        self.webView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view).inset(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0));
        }
        self.webView.sizeToFit();
        //创建网址
        let url = NSURL(string: self.url ?? "")
        //创建请求
        let request = NSURLRequest(url: url! as URL)
        //加载请求
        self.webView.load(request as URLRequest)
        self.view .addSubview(progressView);
        self.progressView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(0)
            make.left.equalTo(self.view).offset(0)
            make.right.equalTo(self.view).offset(0)
            make.height.equalTo(1.0);
        }
        //进度条的进度监听
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.alpha = 1.0
            self.progressView.setProgress(Float(webView.estimatedProgress), animated: true)
            //进度条的值最大为1.0
            if(self.webView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () -> Void in
                    self.progressView.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progressView.progress = 0
                })
            }
        }
    }
    
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {    }
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 加载完毕以后执行，自适应屏幕宽度，有的屏幕不自适应，需要自适应屏幕宽度
        webView.evaluateJavaScript("""
            var oMeta = document.createElement('meta');
            oMeta.content = 'width=device-width, initial-scale=1, user-scalable=0';
            oMeta.name = 'viewport';
            document.getElementsByTagName('head')[0].appendChild(oMeta);
            """,completionHandler: nil)
        // 设置标题
        if titleStr == nil || (titleStr ?? "").isEmpty {
            let script = "document.getElementsByClassName('van-nav-bar__title')[0].innerText"
            webView.evaluateJavaScript(script) { [weak webView] webTitle, error in
                if error == nil, let title = webTitle as? String {
                    self.title = title
                } else if let title = webView?.title {
                    self.title = title
                }
            }
        }
    }
    
    // 处理网页加载失败
    private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError){
        self.progressView.progress = 0
    }
    
    //处理网页加载完成
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!){   }
    
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        self.progressView.progress = 0
    }
    
    open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
                      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url?.absoluteString ?? ""
        decisionHandler(WebNativeActionPolicy.actionPolicy(host: url.trim()) ? .cancel : .allow)
    }
    open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
                      decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
}
